package demo4j;

import apijson.Log;
import apijson.framework.APIJSONApplication;
import apijson.framework.APIJSONCreator;
import apijson.framework.APIJSONSQLConfig;
import apijson.orm.SQLConfig;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import demo4j.model.User;
import demo4j.repo.UserRepository;
import demo4j.utils.WebUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

import static apijson.framework.APIJSONConstant.VISITOR_;
import static apijson.framework.APIJSONConstant.VISITOR_ID;

/**
 * Hello world!
 */
@SpringBootApplication
public class MyAppEntry2 {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(MyAppEntry2.class, args);

        Log.DEBUG = true;
        APIJSONApplication.init(false);
    }

    @Resource
    private UserRepository userRepository;

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(@NonNull CorsRegistry registry) {
                registry.addMapping("/**").allowedOriginPatterns("*").allowedMethods("*").allowCredentials(true).maxAge(3600);
            }

            @Override
            public void addInterceptors(@NonNull InterceptorRegistry registry) {
                registry.addInterceptor(new SaInterceptor(handle -> {
                    if (StpUtil.isLogin()) {
                        long loginId = StpUtil.getLoginIdAsLong();
                        User user = userRepository.findById(loginId);
                        WebUtil.getHttpSession().setAttribute(VISITOR_ID, loginId);
                        WebUtil.getHttpSession().setAttribute(VISITOR_, user);
                    } else {
                        StpUtil.checkLogin();
                    }
                })).addPathPatterns("/**").excludePathPatterns("/login");
            }
        };
    }

    static {
        // 使用本项目的自定义处理类
        APIJSONApplication.DEFAULT_APIJSON_CREATOR = new APIJSONCreator<String>() {
            @Override
            public SQLConfig<String> createSQLConfig() {
                return new APIJSONSQLConfig<>() {
                    @Override
                    public String getDBPassword() {
                        return "123456";
                    }
                };
            }
        };
    }
}
